package com.masterclient.app.businessmodule.minemodule.point;

import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.businessmodule.minemodule.point.adapter.PointProductAdapter;
import com.masterclient.app.businessmodule.minemodule.point.contract.PointProductsContract;
import com.masterclient.app.businessmodule.minemodule.point.contract.PointProductsContractPresenter;
import com.masterclient.app.businessmodule.minemodule.point.model.PointProduct;
import com.masterclient.app.businessmodule.minemodule.point.model.PointProductData;
import com.eoner.baselibrary.utils.GlideUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.status.StatusBarUtil;
import com.masterclient.app.modules.goods.newpage.activity.NewCommodityDetailActivity;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static com.eoner.baselibrary.utils.ScreenUtils.dp2px;

public class PointProductsActivity extends BaseActivity<PointProductsContractPresenter> implements PointProductsContract.View {

    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;

    @BindView(R.id.iv_back_top)
    ImageView ivBackTop;


    private PointProductAdapter adapter;
    private List<PointProduct> goodList = new ArrayList<>();

    private int page = 1;
    private ViewHolder viewHolder;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.point_products);
        ButterKnife.bind(this);

        StatusBarUtil.setStatusBarColor(getActivity(), Color.parseColor("#FFFFFF"));


        init();

        addListener();

        getData();


    }

    private void getData() {
        if (mPresenter != null)
            mPresenter.getPointProductsData("" + page);

    }

    private void init() {
        View headView = View.inflate(mContext, R.layout.view_point_products_head, null);
        viewHolder = new ViewHolder(headView);
        GridLayoutManager layoutManage = new GridLayoutManager(mContext, 2);
        recyclerView.setLayoutManager(layoutManage);
        RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                if (parent.getChildLayoutPosition(view) != 0){
                    outRect.bottom = dp2px(9);
                    //除了第一行每行都只有2个
                    if (parent.getChildLayoutPosition(view) % 2 == 0) {
                        outRect.left = dp2px(4);
                        outRect.right = dp2px(16);
                    } else {
                        outRect.left = dp2px(16);
                        outRect.right = dp2px(4);
                    }
                }
            }
        };
        recyclerView.addItemDecoration(decoration);
        adapter = new PointProductAdapter();
        recyclerView.setAdapter(adapter);
        adapter.bindToRecyclerView(recyclerView);
        adapter.addHeaderView(headView);

        View emptyView = View.inflate(mContext, R.layout.null_search, null);
        adapter.setEmptyView(emptyView);
        emptyView.setVisibility(View.GONE);

        adapter.setHeaderAndEmpty(true);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp2px(300));
        adapter.getEmptyView().setLayoutParams(params);
    }

    private void addListener() {

        ivBackTop.setOnClickListener(v -> recyclerView.smoothScrollToPosition(0));

        adapter.setOnItemClickListener((adapter, view, position) -> {
            if (goodList != null && goodList.size() > position) {
                startActivitry(NewCommodityDetailActivity.class, new String[][]{{"id", goodList.get(position).getSh_id()}, {"convert", "1"}});
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                int[] location = new int[2];
//                holder.llSelector.getLocationOnScreen(location);
//
//                if (location[1] <= ll_location[1]) {
//                    llSelector.setVisibility(View.VISIBLE);
//                } else {
//                    llSelector.setVisibility(View.GONE);
//                }
            }
        });


//        recyclerView.setOnTouchListener(
//                new View.OnTouchListener() {
//                    @Override
//                    public boolean onTouch(View v, MotionEvent event) {
//                        if (swipeLayout.isRefreshing()) {
//                            return true;
//                        } else {
//                            return false;
//                        }
//                    }
//                }
//        );


        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();
                // 当不滚动时
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                // 判断是否滚动超过一屏
                if (firstVisibleItemPosition == 0) {
                    ivBackTop.setVisibility(View.INVISIBLE);
                } else {
                    ivBackTop.setVisibility(View.VISIBLE);
                }

//              } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {//拖动中
//                    ivBackTop.setVisibility(View.INVISIBLE);
//              }
            }
        });


        adapter.setOnLoadMoreListener(() -> {
            if (sh_has_more) {
                page++;
                getData();
            }
        }, recyclerView);
        swipeLayout.setOnRefreshListener(() -> {
            swipeLayout.setRefreshing(false);
            page = 1;
            getData();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    @OnClick({R.id.rl_back})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.rl_rule:

                break;
        }
    }

    boolean sh_has_more;

    @Override
    public void showData(PointProductData data) {
        if (swipeLayout.isRefreshing()) {
            swipeLayout.setRefreshing(false);
        }
        if (data == null || data.getSh_products() == null) {
            return;
        }

        sh_has_more = data.getSh_products().size() != 0;
        viewHolder.ivHead.getLayoutParams().height = (int) ((ScreenUtils.getScreenWidth() - dp2px(32)) * 13 / 34.0f);
        GlideUtil.displayRoundImage(this, data.getSh_banner() == null?"":data.getSh_banner().getSh_image(), viewHolder.ivHead, 7, R.mipmap.defaults_1);
        if (page == 1) {
            goodList.clear();
            goodList.addAll(data.getSh_products());
            adapter.setNewData(goodList);
        } else {
            adapter.loadMoreComplete();
            goodList.addAll(data.getSh_products());
            adapter.notifyDataSetChanged();
        }

        if (!sh_has_more) {
            adapter.loadMoreEnd();
        }
    }

    @Override
    public void loadFail(String s) {

    }

    @Override
    public void loadError(String s) {

    }

    static class ViewHolder {
        @BindView(R.id.iv_head)
        ImageView ivHead;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
